<template>
	<custom-page title="预约" backgroundColor="#F9F9F9" border-bottom-color="#F9F9F9">
		<template #content>
			<view class="page-content">
				<view class="center-view">
					<view class="bg-white">
						<assistant-info :showFollow="false" :itemData="assistantDetailInfo"></assistant-info>
					</view>
					<view style="height: 16rpx;"></view>
					<view class="tab-row" v-if="addOrderType != 'renewType'">
						<view :class="(reserveType==0)?'tab-item-select':'tab-item'" @click="reserveType=0">
							<view>立即下单</view>
							<view class="tab-indate" v-if="reserveType==0"></view>
						</view>
						<view :class="(reserveType==1)?'tab-item-select':'tab-item'" @click="reserveType=1">
							<view>预约下单</view>
							<view class="tab-indate" v-if="reserveType==1"></view>
						</view>
					</view>
					<view style="height: 1rpx;"></view>
					<view class="row-item" @click="selectStoreClick">
						<view class="title">服务门店：</view>
						<view class="content">{{storeInfoData.name||'请选择服务门店'}}</view>
						<image class="arrow-img" :src="asserts.ic_arrow_right"></image>
					</view>
					<view v-if="reserveType==0">
						<view style="height: 1rpx;"></view>
						<view class="time-hour-row">
							<view :class="(timeHourIndex==index)?'time-hour-item-select':'time-hour-item'" v-for="(item,index) in timeHourData" 
							:key="index" @click="hourItemClick(index)">{{item}}小时</view>
						</view>
					</view>
					
					<view v-if="reserveType==1">
						<view class="row-item" @click="selectStartTimeClick">
							<view class="title">预约开始时间：</view>
							<view class="content">{{startTimeStr||'请选择预约时间'}}</view>
							<image class="arrow-img" :src="asserts.ic_arrow_right"></image>
						</view>
						<view style="height: 1rpx;"></view>
						<view class="row-item" @click="selectEndTimeClick">
							<view class="title">预约结束时间：</view>
							<view class="content">{{endTimeStr || '请选择预约时间'}}</view>
							<image class="arrow-img" :src="asserts.ic_arrow_right"></image>
						</view>
					</view>
					
					<view style="height: 16rpx;"></view>
					<view class="row-item">
						<view class="title">订单总价：</view>
						<view class="info">¥{{orderMoneyInfo.totalPaymentStr}}</view>
					</view>
					<view style="height: 1rpx;"></view>
					<view class="row-item">
						<view class="title">支付方式：</view>
						<view class="info">微信支付</view>
					</view>
				</view>
				
			</view>
		</template>
		<template #foot>
			<view class="bottom-layout">
				<view>实付款：</view>
				<view class="price">¥{{orderMoneyInfo.totalPaymentStr}}</view>
				<view class="btn-view" @click="reserveClick">立即预约</view>
			</view>
		</template>
		<template #popup>
			<assistant-reserve-store-popup ref="storePopup" @storeInfoSelectBack="storeInfoSelectBack">
			</assistant-reserve-store-popup>
			<assistant-reserve-time-popup ref="startTimePopup" @timeSelectBack="startTimeSelectBack">
			</assistant-reserve-time-popup>
			<assistant-reserve-time-popup ref="endTimePopup" @timeSelectBack="endTimeSelectBack">
			</assistant-reserve-time-popup>
		</template>
	</custom-page>
</template>

<script>
	import {
		getTimeMills,
		getFormatTime
	} from '../../utils/utils'
	export default {
		data() {
			return {
				assistantId: '',
				assistantDetailInfo: {},
				storeInfoData: {},
				startTimeStr: '',
				endTimeStr: '',
				orderMoneyInfo: {},
				reserveType: 0,		//预约类型
				addOrderType: '', //续单
				renewOrderNo: '', //续单订单编号
				timeHourData: [1, 2, 3, 4, 5, 6, 7, 8],
				timeHourIndex: -1,
			}
		},
		onLoad(val) {
			console.log("onLoad", val)
			this.assistantId = val.userId
			
			this.addOrderType = val.addOrderType
			this.renewOrderNo = val.orderNo

			if (val.storeInfoId && val.storeInfoName) {
				this.storeInfoData.id = val.storeInfoId
				this.storeInfoData.name = val.storeInfoName
			}
			this.getAssistantDetail(this.assistantId)
		},
		methods: {
			//助教详情
			getAssistantDetail(userId) {
				this.requestCenter.getAssistantDetail(userId).then(res => {
					this.assistantDetailInfo = res
				})
			},

			//点击选择门店
			selectStoreClick() {
				this.$refs.storePopup.show()
			},
			//门店选择回调
			storeInfoSelectBack(data) {
				this.storeInfoData = data.data
			},
			
			//时间点击
			hourItemClick(index){
				if (!this.storeInfoData.id) {
					uni.showToast({
						title: "请选择服务门店"
					})
					return
				}
				this.timeHourIndex = index
				this.getOrderMoney()
			},

			//点击开始时间
			selectStartTimeClick() {
				if (!this.storeInfoData.id) {
					uni.showToast({
						title: "请选择服务门店"
					})
					return
				}
				this.$refs.startTimePopup.show('请选择服务开始时间')
			},
			startTimeSelectBack(time) {
				if (!this.calSelectTime(time, this.endTimeStr)) {
					return
				}
				let businessHoursStart = getFormatTime(time, 'ymd') + ' ' + this.assistantDetailInfo.businessHoursStart
				if ((getTimeMills(time) < getTimeMills(businessHoursStart)) && this.assistantDetailInfo
					.businessHoursStart != '00:00') {
					uni.showToast({
						title: "选择的助教不在服务时间"
					})
					return
				}
				let storeBusinessHoursStart = getFormatTime(time, 'ymd') + ' ' + this.storeInfoData.businessHoursStart
				if (getTimeMills(time) < getTimeMills(storeBusinessHoursStart)) {
					uni.showToast({
						title: "选择的门店不在营业时间"
					})
					return
				}
				this.startTimeStr = time
				this.getOrderMoney()
			},

			//结束时间
			selectEndTimeClick() {
				if (!this.storeInfoData.id) {
					uni.showToast({
						title: "请选择服务门店"
					})
					return
				}
				this.$refs.endTimePopup.show('请选择服务结束时间')
			},
			endTimeSelectBack(time) {
				if (!this.calSelectTime(this.startTimeStr, time)) {
					return
				}
				let businessHoursEnd = getFormatTime(time, 'ymd') + ' ' + this.assistantDetailInfo.businessHoursEnd
				if ((getTimeMills(time) > getTimeMills(businessHoursEnd)) && this.assistantDetailInfo.businessHoursEnd !=
					'00:00') {
					uni.showToast({
						title: "选择的助教不在服务时间"
					})
					return
				}
				let storeBusinessHoursEnd = getFormatTime(time, 'ymd') + ' ' + this.storeInfoData.businessHoursEnd
				if (getTimeMills(time) > getTimeMills(storeBusinessHoursEnd)) {
					uni.showToast({
						title: "选择的门店不在营业时间"
					})
					return
				}
				this.endTimeStr = time
				this.getOrderMoney()
			},

			calSelectTime(start, end) {
				if (start && end) {
					if (getTimeMills(start) > getTimeMills(end)) {
						uni.showToast({
							title: "结束时间不能小于开始时间"
						})
						return false
					}
					if (start == end) {
						uni.showToast({
							title: "选择时间不能相同"
						})
						return false
					}
					return true
				}
				return true
			},

			//获取显示支付金额
			getOrderMoney() {
				if (this.addOrderType == 'renewType') { //续单计算金额
					let params = {
						orderNo: this.renewOrderNo,
						renewHoursTime: this.timeHourData[this.timeHourIndex]
					}
					this.requestCenter.renewCalculateMoney(params).then(res => {
						this.orderMoneyInfo = res
					})
				} else {
					if(this.reserveType == 1){		//预约下单
						if (this.startTimeStr && this.endTimeStr && this.assistantId && this.storeInfoData.id) {
							let params = {
								assistantId: this.assistantId,
								pollId: this.storeInfoData.id,
								serviceStartTime: getTimeMills(this.startTimeStr),
								serviceEndTime: getTimeMills(this.endTimeStr),
							}
							this.requestCenter.getOrderMoney(params).then(res => {
								this.orderMoneyInfo = res
							})
						}
					}else{		//实时下单
						let params = {
							assistantId: this.assistantId,
							pollId: this.storeInfoData.id,
							orderBookedType: 2,			//实时订单
							totalTime: this.timeHourData[this.timeHourIndex]
						}
						this.requestCenter.getOrderMoney(params).then(res => {
							this.orderMoneyInfo = res
						})
					}
				}
				
			},

			//点击立即预约
			reserveClick() {
				if (!this.storeInfoData.id) {
					uni.showToast({
						title: "请选择服务门店"
					})
					return
				}
				if(this.reserveType == 1){
					if (!this.startTimeStr) {
						uni.showToast({
							title: "请选择预约开始时间"
						})
						return
					}
					if (!this.endTimeStr) {
						uni.showToast({
							title: "请选择预约结束时间"
						})
						return
					}
					if (getTimeMills(this.startTimeStr) < (new Date().getTime())) {
						uni.showToast({
							title: "不能选择现在之前的时间"
						})
						return
					}
					if (getTimeMills(this.startTimeStr) > getTimeMills(this.endTimeStr)) {
						uni.showToast({
							title: "结束时间不能小于开始时间"
						})
						return
					}
				}else{
					if (this.timeHourIndex == -1) {
						uni.showToast({
							title: "请选择预约小时"
						})
						return
					}
				}
				
				uni.showModal({
					title: '确定预约吗？',
					success: (modal) => {
						if (modal.confirm) {
							if (this.addOrderType == 'renewType') { //续单--下单
								let params = {
									orderNo: this.renewOrderNo,
									renewHoursTime: this.timeHourData[this.timeHourIndex]
								}
								this.requestCenter.renewOrder(params).then(orderRes => {
									if (orderRes) {
										this.wxPay(orderRes)
									}
								})
							} else {
								if(this.reserveType == 1){		//预约下单
									let params = {
										assistantId: this.assistantId,
										pollId: this.storeInfoData.id,
										serviceStartTime: getTimeMills(this.startTimeStr),
										serviceEndTime: getTimeMills(this.endTimeStr),
										orderBookedType: 1,			//预约下单
									}
									// #ifdef APP-PLUS
									this.requestCenter.addOrderApp(params).then(orderRes => {
										console.log(orderRes);
										if (orderRes) {
											this.wxAppPay(orderRes)
										}
									})
									// #endif
									// #ifdef MP-WEIXIN
									this.requestCenter.addOrder(params).then(orderRes => {
										if (orderRes) {
											this.wxPay(orderRes)
										}
									})
									// #endif
								}else{		//实时下单
									let params = {
										assistantId: this.assistantId,
										pollId: this.storeInfoData.id,
										orderBookedType: 2,			//实时订单
										totalTime: this.timeHourData[this.timeHourIndex]
									}
									// #ifdef APP-PLUS
									this.requestCenter.addOrderApp(params).then(orderRes => {
										console.log(orderRes);
										if (orderRes) {
											this.wxAppPay(orderRes)
										}
									})
									// #endif
									// #ifdef MP-WEIXIN
									this.requestCenter.addOrder(params).then(orderRes => {
										if (orderRes) {
											this.wxPay(orderRes)
										}
									})
									// #endif
								}
							}
						}
					}
				})
			},

			wxH5pay(data) {
				function onBridgeReady(data) {
					window.WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							"appId": data.appId, //公众号
							"timeStamp": data.timeStamp, //时间戳
							"nonceStr": data.nonceStr, //随机串
							"package": data.package, //prepay_id
							"signType": data.signType, //微信签名方式RSA
							"paySign": data.paySign //微信签名
						},
						function(res) {
							uni.redirectTo({
								url: '/pages/player-order-list/player-order-list'
							})
							if (res.err_msg == "get_brand_wcpay_request:ok") {}
							// 支付过程中用户取消
							if (res.err_msg == "get_brand_wcpay_request:cancel") {}
							// 支付失败
							if (res.err_msg == "get_brand_wcpay_request:fail") {}
						});
				}
				if (typeof WeixinJSBridge == "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', onBridgeReady(data), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', onBridgeReady(data));
						document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(data));
					}
				} else {
					onBridgeReady(data);
				}
			},
			
			//APP支付
			wxAppPay(orderRes){
				let rousePayParams = {
					orderNo: orderRes.orderNo,
				}
				this.requestCenter.rouseOrderPay(rousePayParams).then(payRes => {
					console.log("payRes: " + JSON.stringify(payRes));
					uni.requestPayment({
					    "provider": "wxpay",
					    "orderInfo": {
					        "appid": payRes.appId,  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
					        "noncestr": payRes.nonceStr, // 随机字符串
					        "package": payRes.package,        // 固定值
					        "partnerid": payRes.partnerId,      // 微信支付商户号
					        "prepayid": payRes.prepayId, // 统一下单订单号
					        "timestamp": payRes.timeStamp,        // 时间戳（单位：秒）
					        "sign": payRes.sign     // 签名，这里用的 MD5/RSA 签名
					    },
					    success: ((payRes) => {
					    	this.payResultBack("支付成功")
					    }),
					    fail: ((err) => {
					    	this.payResultBack("支付失败")
					    })
					})
				})
			},

			//微信支付
			wxPay(orderRes) {
				// #ifdef MP-WEIXIN
				uni.login({
					provider: 'weixin', //使用微信登录
					success: (loginRes) => {
						let rousePayParams = {
							orderNo: orderRes.orderNo,
							wxCode: loginRes.code
						}
						this.requestCenter.rouseOrderPay(rousePayParams).then(payRes => {
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: payRes.timeStamp,
								nonceStr: payRes.nonceStr,
								package: payRes.package,
								signType: payRes.signType,
								paySign: payRes.paySign,
								success: ((payRes) => {
									this.payResultBack("支付成功")
								}),
								fail: ((err) => {
									this.payResultBack("支付失败")
								})
							});
						})
					}
				});
				// #endif
				// #ifdef H5
				// let rousePayParams = {
				// 	orderNo: orderRes.orderNo,
				// }
				// this.requestCenter.rouseOrderPay(rousePayParams).then(payRes => {
				// let that = this;
				// let en = window.navigator.userAgent.toLowerCase();
				// if (en.match(/MicroMessenger/i) == 'micromessenger') {// 微信内置浏览器
				// 	that.wxH5pay(payRes)
				// }else{
				
				// }
				// })
				// #endif
			},
			
			payResultBack(title){
				uni.showToast({
					title: title,
					duration: 500,
					complete: () => {
						uni.redirectTo({
							url: '/pages/player-order-list/player-order-list'
						})
					}
				})
			}

		}
	}
</script>

<style scoped lang="less">
	.page-content {
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.center-view {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.bg-white {
		background-color: white;
	}

	.tab-row {
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: white;

		.tab-item,
		.tab-item-select {
			flex: 1;
			height: 88rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			line-height: 38rpx;
		}

		.tab-item {
			color: #101413;
		}

		.tab-item-select {
			color: #01CBFF;
		}

		.tab-indate {
			width: 100rpx;
			height: 8rpx;
			background: #01CBFF;
			box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(1, 203, 255, 0.16);
			border-radius: 4rpx 4rpx 4rpx 4rpx;
			margin-top: 8rpx;
		}
	}
	
	.time-hour-row{
		display: flex;
		flex-direction: row;
		align-self: center;
		flex-wrap: wrap;
		padding: 32rpx 0 0 24rpx;
		box-sizing: border-box;
		background-color: white;
		.time-hour-item,
		.time-hour-item-select{
			width: 160rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #E3FCFF;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			margin-right: 20rpx;
			font-size: 28rpx;
			color: #101413;
			margin-bottom: 32rpx;
		}
		.time-hour-item-select{
			border: 1rpx solid #01CBFF;
		}
	}

	.row-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 100rpx;
		line-height: 100rpx;
		padding: 0 32rpx;
		box-sizing: border-box;
		background-color: white;

		.title {
			font-size: 28rpx;
			color: #585F70;
			line-height: 48rpx;
		}

		.content {
			flex: 1;
			text-align: end;
			font-size: 28rpx;
			color: #021624;
			line-height: 48rpx;
			font-weight: bold;
		}

		.info {
			flex: 1;
			text-align: end;
			font-size: 28rpx;
			color: #585F70;
			line-height: 48rpx;
		}

		.arrow-img {
			width: 20rpx;
			height: 21rpx;
			margin-left: 18rpx;
		}
	}

	.bottom-layout {
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: white;
		padding: 6rpx 32rpx;
		box-sizing: border-box;
		font-size: 32rpx;
		color: #585F70;

		.price {
			flex: 1;
			font-size: 32rpx;
			color: #ED3C3D;
			margin-left: 10rpx;
		}

		.btn-view {
			background-color: #01CBFF;
			border-radius: 44rpx;
			width: 240rpx;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}
</style>
